﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Reflector.cs" company="Data Ductus Malmö">
//   (c) 2010 - 2012 Data Ductus Malmö AB
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DataDuctus.Snmp.Persistor.Core.Persistor.Internal
{
  using System;

  using DataDuctus.Snmp.Persistor.Core.MetaData;

  using Lextm.SharpSnmpLib;

  /// <summary>
  /// The reflector.
  /// </summary>
  internal class Reflector
  {
    #region Methods

    /// <summary>
    /// Set the <paramref name="value"/> onto a property in <paramref name="instance"/>.
    /// </summary>
    /// <param name="index">
    /// The suboid to set.
    /// </param>
    /// <param name="meta">
    /// The <paramref name="instance"/> metadata.
    /// </param>
    /// <param name="instance">
    /// The instance whose property to be set.
    /// </param>
    /// <param name="value">
    /// The value to be set on the property.
    /// </param>
    /// <returns>
    /// If property is found and set true, otherwise false or an exception is thrown.
    /// </returns>
    /// <exception cref="Exception">
    /// When underlying property in the <paramref name="instance"/> is throwning an exception, this is not
    /// caught.
    /// </exception>
    internal static bool SetProperty(int index, ClassMeta meta, object instance, ISnmpData value)
    {
      PropertyMeta property;

      if (!meta.TryGetPropertyMetaBySubOid(index, out property))
      {
        return false;
      }

      object convertedValue = DataConverter.ConvertToEntityType(property, value);

      property.Property.SetValue(instance, convertedValue, null /*noIndex*/);

      return true;
    }

    #endregion
  }
}